package com.writing.controller;

import com.writing.common.Result;
import com.writing.entity.User;
import com.writing.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {
    
    private final UserService userService;
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<Map<String, Object>> register(@RequestBody @Valid RegisterRequest request) {
        try {
            User user = userService.register(request.getUsername(), request.getEmail(), request.getPassword());
            
            Map<String, Object> data = new HashMap<>();
            data.put("id", user.getId());
            data.put("username", user.getUsername());
            data.put("email", user.getEmail());
            data.put("nickname", user.getNickname() != null ? user.getNickname() : user.getUsername());
            
            return Result.success("注册成功", data);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody @Valid LoginRequest request) {
        try {
            String token = userService.login(request.getUsername(), request.getPassword());
            
            // 获取登录后的用户信息
            User user = null;
            if (request.getUsername().contains("@")) {
                // 如果输入的是邮箱，通过邮箱查找
                user = userService.findByEmail(request.getUsername());
            } else {
                // 如果输入的是用户名，通过用户名查找
                user = userService.findByUsername(request.getUsername());
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);

            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("username", user.getUsername());
            userInfo.put("email", user.getEmail());
            userInfo.put("nickname", user.getNickname() != null ? user.getNickname() : user.getUsername());
            userInfo.put("avatar", user.getAvatar() != null ? user.getAvatar() : "");
            userInfo.put("role", user.getRole() != null ? user.getRole() : "USER");

            data.put("user", userInfo);
            
            return Result.success("登录成功", data);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public Result<Map<String, Object>> getCurrentUser(@RequestAttribute("userId") Long userId) {
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        Map<String, Object> data = new HashMap<>();
        data.put("id", user.getId());
        data.put("username", user.getUsername());
        data.put("email", user.getEmail());
        data.put("nickname", user.getNickname() != null ? user.getNickname() : user.getUsername());
        data.put("avatar", user.getAvatar() != null ? user.getAvatar() : "");
        data.put("role", user.getRole() != null ? user.getRole() : "USER");

        return Result.success(data);
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/profile")
    public Result<Map<String, Object>> updateProfile(@RequestAttribute("userId") Long userId,
                                                     @RequestBody UpdateProfileRequest request) {
        try {
            log.info("更新用户信息请求，用户ID: {}", userId);

            User user = userService.getById(userId);
            if (user == null) {
                log.warn("用户不存在，用户ID: {}", userId);
                return Result.error("用户不存在");
            }

            // 更新用户信息
            if (request.getNickname() != null) {
                user.setNickname(request.getNickname());
            }
            if (request.getEmail() != null) {
                // 检查邮箱是否已被其他用户使用
                User existingUser = userService.findByEmail(request.getEmail());
                if (existingUser != null && !existingUser.getId().equals(userId)) {
                    return Result.error("邮箱已被其他用户使用");
                }
                user.setEmail(request.getEmail());
            }
            if (request.getAvatar() != null) {
                user.setAvatar(request.getAvatar());
            }

            userService.updateById(user);

            // 返回更新后的用户信息
            Map<String, Object> data = new HashMap<>();
            data.put("id", user.getId());
            data.put("username", user.getUsername());
            data.put("email", user.getEmail());
            data.put("nickname", user.getNickname() != null ? user.getNickname() : user.getUsername());
            data.put("avatar", user.getAvatar() != null ? user.getAvatar() : "");
            data.put("role", user.getRole() != null ? user.getRole() : "USER");

            return Result.success("更新成功", data);
        } catch (Exception e) {
            return Result.error("更新失败: " + e.getMessage());
        }
    }
    
    /**
     * 注册请求类
     */
    public static class RegisterRequest {
        private String username;
        private String email;
        private String password;
        
        // getters and setters
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }
    
    /**
     * 登录请求类
     */
    public static class LoginRequest {
        private String username;
        private String password;

        // getters and setters
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }

    /**
     * 更新用户信息请求类
     */
    public static class UpdateProfileRequest {
        private String nickname;
        private String email;
        private String avatar;

        // getters and setters
        public String getNickname() { return nickname; }
        public void setNickname(String nickname) { this.nickname = nickname; }
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
        public String getAvatar() { return avatar; }
        public void setAvatar(String avatar) { this.avatar = avatar; }
    }
}
